import hashlib
import fitz  # PyMuPDF
import requests
from datetime import datetime
import sys

def calculate_md5(file_path):
    """Calculate the MD5 hash of a file."""
    md5_hash = hashlib.md5()
    with open(file_path, "rb") as f:
        for byte_block in iter(lambda: f.read(4096), b""):
            md5_hash.update(byte_block)
    return md5_hash.hexdigest()

def read_content_from_file(file_path):
    """Read content from a text file."""
    with open(file_path, "r", encoding="utf-8") as f:
        return f.read()

def send_post_request(pdf_file_path, content_file_path, pdf_name,ai_report_file_path):
    """Send a POST request to the server with PDF metadata and MD5 token."""
    md5_token = calculate_md5(pdf_file_path)
    current_time = datetime.now().isoformat()
    content = read_content_from_file(content_file_path)
    ai_report = read_content_from_file(ai_report_file_path)
   
    print("ai_report",ai_report)
    payload = {
        "content": content,
        "fileType": "pdf",
        "name": pdf_name,
        "checked":0,
        "nt": current_time,
        "rawFile": pdf_file_path,  # Assuming rawFile is not needed or can be empty
        "token": md5_token,
        "aiReport":ai_report,
    }

    headers = {
        "Accept": "application/json, text/plain, */*",
        "Accept-Language": "zh-CN,zh;q=0.9",
        "Content-Type": "application/json"
    }

    response = requests.post("http://127.0.0.1:8888/geological_data_mgr/resourcefile/createObj", json=payload, headers=headers)

    if response.status_code == 200:
        print("Request was successful:", response.json())
    else:
        print("Request failed with status code:", response.status_code)
        print("Response:", response.text)

def main():
    if len(sys.argv) != 4:
        print("Usage: python script.py <path_to_pdf> <path_to_text>")
        sys.exit(1)

    pdf_file_path = sys.argv[1]
    content_file_path = sys.argv[2]
    ai_report_file_path = sys.argv[3]
    pdf_name = pdf_file_path.split('/')[-1]  # Extracts the filename from the path
    pdf_name = pdf_name.split('\\')[-1]  # Extracts the filename from the path

    send_post_request(pdf_file_path, content_file_path, pdf_name,ai_report_file_path)

if __name__ == "__main__":
    main()


